package com.gxpt.app.view;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.R;
import com.gxpt.app.adapter.assesslist_Adapter;
import com.gxpt.app.adapter.jiahomepage_Adapter;
import com.gxpt.app.bean.assesslist_bean;
import com.gxpt.app.bean.jiahomepage_bean;
import com.gxpt.app.bean.myinfo_bean;
import com.utils.ScreenUtils;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_common_list)
public class Activity_life_user_detail extends BaseActivity {

    /**服务器端一共多少条数据*/
    private static final int TOTAL_COUNTER = 10000;//如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断

    /**每一页展示多少条数据*/
    private static final int REQUEST_COUNT = 20;

    /**已经获取到多少条数据了*/
    private static int mCurrentCounter = 0;

    private jiahomepage_Adapter mDataAdapter = null;

    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;

    ///////////////////
    int page_num  = 1;
    int page_size = 20;


    @ViewInject(R.id.mLRecyclerView)
    LRecyclerView mLRecyclerView;


    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;


    TextView txt_mem_tel;
    TextView txt_count;


    String ID;

    //////view1
    private View topView;

    private ConvenientBanner convenientBanner;//顶部广告栏控件
    private ArrayList<Integer> localImages = new ArrayList<Integer>();
    private List<String> networkImages;
    private String[] images = {"http://www.jikew.cn/uploads/image/focus/2017/0328/20170328155439_28832.jpg#####999#####0"};

    int pic_hight;//轮播图高度

;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle b = new Bundle();
        b =getIntent().getBundleExtra("DATA");
        if(b != null){
            ID = b.getString("ID");
        }
//        Logger.i("ID = "+ID);



        x.view().inject(this);
        initView();
        initData();
    }


    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_gaiyonghuxinxi));

        try {
            pic_hight = ScreenUtils.getScreenWidth(context) / 16 * 10;//16:9高
        } catch (Exception e) {
            pic_hight = 600;
        }

        initBars();
        ///////////////////////////////////////////
        mDataAdapter = new jiahomepage_Adapter(context);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mLRecyclerView.setAdapter(mLRecyclerViewAdapter);

//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.split)
//                .build();

        mLRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        mLRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mLRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mLRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //add a HeaderView
        mLRecyclerViewAdapter.addHeaderView(topView);


        mLRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDataAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
                mCurrentCounter = 0;
                do_Refresh();
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能

        mLRecyclerView.setLoadMoreEnabled(true);

        mLRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                do_LoadMore();
            }
        });

        //设置头部加载颜色
        mLRecyclerView.setHeaderViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载颜色
        mLRecyclerView.setFooterViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载文字提示
        mLRecyclerView.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        mLRecyclerView.refresh();

        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {

//                    assesslist_bean.assesslist item = mDataAdapter.getDataList().get(position);

//                    Intent gonew =new Intent();
//                    gonew.setClass(context,Activity_life_need_detail.class);
//                    gonew.putExtra("ID",Integer.parseInt(item.store_id));
//                    startActivity(gonew);

                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
//                ItemModel item = mDataAdapter.getDataList().get(position);
//                T.show(getApplicationContext(), "onItemLongClick - " + item.title,1);
            }
        });
    }

    private void initBars(){
        topView = LayoutInflater.from(context).inflate(R.layout.common_life_user_detail_main,null, false);
        topView.setLayoutParams(new LRecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));

        txt_mem_tel = (TextView) topView.findViewById(R.id.txt_mem_tel);
        txt_count   = (TextView) topView.findViewById(R.id.txt_count);
    }

    private void setDATA(jiahomepage_bean.jiahomepage data){
        txt_mem_tel.setText(data.mem_tel);
        txt_count.setText(String.format(getResources().getString(R.string.txt_life_count),data.count));
    }


    @Override
    public void initData() {

    }

    private void do_Refresh(){
        page_num = 1;
        Net_jiahomepage();//最新

    }

    private void do_LoadMore(){
        page_num += 1;
        Net_jiahomepage();//最新
    }
    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(ArrayList<jiahomepage_bean.jiahomepage.demand> list) {

        mDataAdapter.addAll(list);
        mCurrentCounter += list.size();
    }



    @Event(value={R.id.toback})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
        }
    }






    //////NET DO

    private void Net_jiahomepage(){
        Logger.i("ID2 = "+ID);
         JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "member");
            jsonBody.put("serviceName",          "jiahomepage");

            jsonBody.put("member_id",             ID);
            jsonBody.put("area_id",                  "");
            jsonBody.put("page_num",              page_num);
            jsonBody.put("page_size",             page_size);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i(" = "+jsonBody.toString()+" ["+Constant.URL_jiahomepage+"]");
        HttpUtils.http_post_string(Constant.URL_jiahomepage,jsonBody.toString(),do_jiahomepage);
    }

    StringCallback do_jiahomepage = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
            Logger.e("= "+s);
            try{
                jiahomepage_bean data = new Gson().fromJson(s, jiahomepage_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        setDATA(data.data);
                        if(data.data.demand_rs.size()>0){
                            addItems((ArrayList)data.data.demand_rs);
                            notifyDataSetChanged();
                        }else{
                            page_num -= 1;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };


}
